package servlet;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;

import pojo.OrderInfo;
import pojo.User;

/**
 * Servlet implementation class AddServlet
 */
public class AddServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	 Logger logger=Logger.getLogger(ViewCartServlet.class);  
	 
    public AddServlet() {
        super();
        
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html);charset=utf-8");
		logger.info(((User)request.getSession().getAttribute("user")).getName()+"cart");
		String bidString=request.getParameter("b_id");
		String name=request.getParameter("name");
		
		Map<String, OrderInfo> carts=(Map<String, OrderInfo>)request.getSession().getAttribute("cart");
		if(null==carts)
		{
			carts=new HashMap<>();
		}
		if(carts.containsKey(bidString))
		{
			OrderInfo info=carts.get(bidString);
			int count=info.getCount();
			info.setCount(++count);
		}else {
			OrderInfo info=new OrderInfo();
			info.setBidString(bidString);
			info.setName(name);
			info.setCount(1);
			info.setUidString(((User)request.getSession().getAttribute("user")).getId());
			carts.put(bidString,info);
		}
		logger.info(((User)request.getSession().getAttribute("user")).getName()+"put book into vart");
		request.getSession().setAttribute("info", "加购物车");
		request.getRequestDispatcher("store").forward(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
